<template>
	<view class="medicalRecordDetails">
		<view class="medicalRecordDetails-list">
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">就诊宠物：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail.pets.name}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">是否绝育：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail.pets.sterile_text}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">性别：</text>
					<text class="medicalRecordDetails-list-inner-right">{{['未知', '公', '母'][medicalDetail.pets.gender]}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">品种：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail.pets.category?.name}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">年龄：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail.pets.birthday}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">体重：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail?.pets?.weight}}公斤</text>
				</view>
			</view>
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">预约人：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail?.user?.nickname}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">联系电话：</text>
					<text class="medicalRecordDetails-list-inner-right">{{medicalDetail?.user?.mobile}}</text>
				</view>
				<view class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left">日期：</text>
					<text class="medicalRecordDetails-list-inner-right">{{formatDate(medicalDetail?.createtime)}}</text>
				</view>
			</view>
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-title">
					患者主诉
					<image class="editimg" @tap="edit()" :src="`${prefix_image}/homepage/IntegralRecord/doctorEdit.png`" mode="aspectFit" />
				</view>
				<view class="medicalRecordDetails-list-inner-content">{{medicalDetail.description}}</view>
			</view>
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-title">
					检查结果图片上传
				</view>
				<view class="img_list">
					<view class="upload_box" v-for="(item, index) in imgList" :key="index">
						<image :src="item.fullurl" mode="aspectFit" />
						<view class="clear" @click="deleteImg(index)">
							<text>x</text>
						</view>
					</view>
					<view v-if="imgList.length < 10" class="upload_box" @click="uploadImg">
						<image src="@/static/upload@2x.png" mode="" />
					</view>
				</view>
			</view>
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-title">
					补充生理信息视频
				</view>
				<view class="medicalRecordDetails-list-inner-title2">请近距离拍摄宠物完整身体</view>
				<view class="upload_box">
					<video v-if="videoSrc !== '' && videoSrc !== undefined" :src="videoSrc" controls></video>
					<image v-else src="@/static/upload@2x.png" mode="" @click="gotoPreviewVideo(0)" />
				</view>
				<view class="medicalRecordDetails-list-inner-title2">(选填) 请近距离拍摄局部重点病症部位或肢体</view>
				<view class="video_list">
					<view class="upload_box" v-for="(item, index) in videoList" :key="index">
						<video :src="item.videoSrc" controls></video>
					</view>
					<view v-if="videoList.length < 9" class="upload_box" @click="gotoPreviewVideo(1)">
						<image src="@/static/upload@2x.png" mode="" />
					</view>
				</view>
			</view>
			<view class="medicalRecordDetails-list-inner">
				<view class="medicalRecordDetails-list-inner-list" style="justify-content: space-between;">
					<text class="medicalRecordDetails-list-inner-left">预约复诊</text>
					<view class="medicalRecordDetails-list-inner-right" style="display: flex;">
						<view>
							<radio value="r1" :checked="radioIndex === 1" @click="radioIndex = 1" />
							<text style="margin-left: 5px;">是</text>
						</view>
						<view style="margin-left: 20px;">
							<radio value="r2" :checked="radioIndex === 0" @click="radioIndex = 0" />
							<text style="margin-left: 5px;">否</text>
						</view>
					</view>
				</view>
				<view v-if="radioIndex === 1" class="medicalRecordDetails-list-inner-list">
					<text class="medicalRecordDetails-list-inner-left" style="padding-right: 20rpx">预约复诊时间</text>
					<!-- <uni-datetime-picker returnType="timestamp" v-model="single" @change="changeLog($event)"  /> -->
					<uni-datetime-picker hide-second=true returnType="timestamp" type="datetime" :clear-icon="false" v-model="single" @change="changeLog($event)"  />
				</view>
				<view class="medicalRecordDetails-list-inner-list" style="justify-content: space-between;">
					<text class="medicalRecordDetails-list-inner-left">随访方案</text>
					<view class="medicalRecordDetails-list-inner-right" style="display: flex;" @click="goFllowPlan">
						<text v-if="!followPlan.name">请选择</text>
						<text v-else>{{followPlan.name}}</text>
						<uni-icons type="right" size="24" color="#adadad"></uni-icons>
					</view>
				</view>
			</view>
		</view>
		<!-- 底部按钮 -->
		<view class="medicalRecords-btn">
			<view class="medicalRecords-btn-save" @tap="handleConfirm">
				保存
			</view>
			<view class="medicalRecords-btn-confirm" @tap="handleConfirm">
				确认
			</view>
		</view>
	</view>
</template>

<script>
	import store from '@/store';
	import config from '@/hooks/useConfig.js'
	import {
		defineComponent,
		reactive,
		toRefs,
		getCurrentInstance,
		computed
	} from "vue"
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	
	export default defineComponent({
		setup(props) {
			const {
				height,
				statusBarHeight
			} = store.state.phoneInfo
			const {
				prefix_image,
				prefix_api
			} = config()
			const data = reactive({
				caseId: '',
				medicalDetail: {
					pets: {},
					user: {},
					description: ''
				},
				radioIndex: 1, // 是否预约复诊 0: 是 1: 否
				imgList: [],
				// 随访方案
				followPlan: {
					id: '',
					name: ''
				},
				videoList: [],
				videoSrc: '',
				imgSrc: '',
				videoType: null,
				id: "",
				
				backdata: {},
				single: null,
				prefix_image
			})

			onShow(() => {
				let pages = getCurrentPages();
				let curPage = pages[pages.length - 1]
				
				if (![curPage.data.id, curPage.data.name].includes(undefined)) {
					data.followPlan.id = curPage.data.id
					data.followPlan.name = curPage.data.name
				}
				uni.$on("back", res => {
				   if (res.videoSrc) {
				   	if (data.videoType == 0) {
				   		// 主图
				   		data.videoSrc = curPage.data.videoSrc
				   		data.imgSrc = curPage.data.imgSrc
				   	} else if (data.videoType == 1) {
				   		// 多图
				   		data.videoList.push({
				   			videoSrc: curPage.data.videoSrc,
				   			imgSrc: curPage.data.imgSrc
				   		})
				   		console.log('onShow视频', data.videoList)
				   	}
				   }
				    // 清除监听
				    uni.$off('back');
				})
				
				uni.$on("doctorEditBack", res => {
					console.log(res)
					if(res?.textarea){
						data.medicalDetail.description = res?.textarea
					}
				    // 清除监听
				    uni.$off('doctorEditBack');
				})
				
				// pickList: JSON.stringify(this.pickList)
			})

			const {
				appContext: {
					config: {
						globalProperties: global

					},
				},
			} = getCurrentInstance()

			let formatDate = computed(() => {
				return function(time) {
					const date = new Date(time * 1000)
					const year = date.getFullYear()
					const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
					const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
					const hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
					const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
					const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
					return year + '-' + month + '-' + day + ' ' + hour + ':' + minutes + ':' + seconds
				}
			})

			onLoad((option) => {
				console.log('病历详情页面option', option)
				data.caseId = option.id
				// 获取病历详情
				global.$request.post(`/v1/api/cases/info/${option.id}`, {}).then(res => {
					if (res.code === 1) {
						data.medicalDetail = res.data
                        data.radioIndex = Number(res.data.follow)
                        data.followPlan.name = res.data.upvisitlist
						data.id = res?.data?.pets?.category?.pid
					}
				})
			})

			const goFllowPlan = () => {
				uni.navigateTo({
					url: `/pages/followPlan/followPlan?id=${data.id}`
				})
			}

			const gotoPreviewVideo = (type) => {
				data.videoType = type
				uni.navigateTo({
					// 拍视频
					url: '/packageHome/pages/shotVideo/index?medicalDetail=' + JSON.stringify(data.medicalDetail)
				})
			}

			// 上传
			const uploadImg = () => {
				uni.chooseImage({
					count: 1,
					sourceType: ['album', 'camera'],
					success: (res) => {
						let baseUrl = import.meta.env.VITE_APP_API_URL
						uni.uploadFile({
							url: `${baseUrl}/v1/api/common/upload`,
							filePath: res.tempFilePaths[0],
							name: 'file',
							header: {
								'token': uni.getStorageSync('token'),
							},
							success: (uploadFileRes) => {
								let obj = JSON.parse(uploadFileRes.data)
								data.imgList.push(obj.data)
							}
						})
					}
				})
			}

			// 删除图片
			const deleteImg = (index) => {
				data.imgList.splice(index, 1)
			}

			const handleConfirm = () => {
                if (data.imgList.length === 0) {
                    uni.showToast({
                        icon: 'none',
                        title: '请上传检查结果',
                        duration: 2000
                    })
                    return
                }
                if (data.videoSrc === '') {
                    uni.showToast({
                        icon: 'none',
                        title: '请补充生理信息视频',
                        duration: 2000
                    })
                    return
                }
                if (data.radioIndex === 1 && data.followPlan.name === '') {
                    uni.showToast({
                        icon: 'none',
                        title: '请选择随访方案',
                        duration: 2000
                    })
                    return
                }
				
				// 复诊时间
				if(data.radioIndex === 1 && !data.single ){
					uni.showToast({
					    icon: 'none',
					    title: '请选择随访复诊时间',
					    duration: 2000
					})
					return
				}
				
				let mapImg = data.imgList.map(item => {
					return item.fullurl
				})
				let mapVideo = data.videoList.map(item => {
					return item.videoSrc
				})
				let images = mapImg.join()
				let videos = mapVideo.join()
				const params = {
					results: '',
					videofile: data.videoSrc, //视频
					videofiles: videos, // 视频(选填)
					images: images, // 图片
					follow: data.radioIndex, // 是否复诊:0=否,1=是
					// follow_time: 0, // 复诊时间
					// followdesc: '', // 复诊详情
					upvisitlist: data.followPlan.name, // 回访方案
					// upvisitdesc: '' // 回访详情json字符串
					description: data?.medicalDetail?.description,  // 编辑主诉
				}
				console.log('确认params', params)
				global.$request.post(`/v1/api/cases/edit/${data.caseId}`, params).then(res => {
					if (res.code === 1) {
						uni.showToast({
							icon: 'none',
							title: '确认成功',
							duration: 2000
						})
						let pages = getCurrentPages();
						let currPage = pages[pages.length - 1]; //当前页面
						let prevPage = pages[pages.length - 2]; //上一个页面
						//直接调用上一个页面的setData()方法，把数据存到上一个页面中去
						prevPage.setData({
						    tabIndex: props.tabIndex
						})
						
						uni.navigateBack({
							delta: 1
						})
					}
				})
			}
			
			// 编辑主诉
			const edit = () => {
				uni.navigateTo({
					url: `/pages/editPatientComplaint/index?edit=${data.medicalDetail.description}`
				});
			}
			
			// 更改时间
			const changeLog = (e) => {
				data.single = e
				console.log('change事件:', e);
			}

			return {
				...toRefs(data),
				goFllowPlan,
				formatDate,
				handleConfirm,
				uploadImg,
				deleteImg,
				gotoPreviewVideo,
				edit,
				changeLog
			}
		}
	})
</script>

<style lang="stylus" scoped>
	.medicalRecordDetails {
		background: #F6F6F7;
		min-height: 100vh;
		overflow: hidden;

		.medicalRecordDetails-list {
			padding-bottom: 200rpx;

			.medicalRecordDetails-list-inner {
				background-color: #fff;
				padding: 36rpx 32rpx;
				margin-top: 16rpx;

				.img_list {
					padding: 8rpx 8rpx;
					// margin-bottom: 84rpx;
					display: flex;
					flex-wrap: wrap;
				}

				.video_list {
					padding: 8rpx 8rpx;
					// margin-bottom: 84rpx;
					display: flex;
					flex-wrap: wrap;
				}

				.upload_box {
					position: relative;
					margin-right: 10rpx;
					margin-bottom: 10rpx;
					width: 160rpx;
					height: 160rpx;
					background-color: #F7F8F9;

					image {
						width: 100%;
						height: 100%;
					}

					video {
						width: 100%;
						height: 100%;
					}

					.clear {
						position: absolute;
						top: 0;
						right: 0;
						width: 40rpx;
						height: 40rpx;
						text-align: center;
						line-height: 40rpx;
						background-color: #999999;
						color: #D1C7B3;
						opacity: .9;
					}
				}


				.medicalRecordDetails-list-inner-list {
					display: flex;
					padding-bottom: 36rpx;

					.medicalRecordDetails-list-inner-left {
						font-size: 32rpx;
						// font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: #999999;
					}

					.medicalRecordDetails-list-inner-right {
						font-size: 32rpx;
						// font-family: PingFangSC-Regular, PingFang SC;
						font-weight: 400;
						color: #333333;
						align-items: center
					}
				}

				.medicalRecordDetails-list-inner-list:last-of-type {
					padding-bottom: 0rpx;
				}

				.medicalRecordDetails-list-inner-title {
					font-size: 32rpx;
					// font-family: PingFangSC-Semibold, PingFang SC;
					font-weight: 600;
					color: #333333;
					padding-bottom: 24rpx;
					display: flex;
					justify-content: space-between;
					.editimg{
						width: 41rpx;
						height: 41rpx;
					}
				}

				.medicalRecordDetails-list-inner-content {
					font-size: 32rpx;
					// font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #999999;
				}

				.medicalRecordDetails-list-inner-title2 {
					font-size: 28rpx;
					// font-family: PingFangSC-Regular, PingFang SC;
					font-weight: 400;
					color: #999999;
					margin-bottom: 20rpx;
				}
			}
		}

		.medicalRecords-btn {
			position: fixed;
			left: 0;
			bottom: 0;
			background-color: #fff;
			padding: 32rpx 0;
			width: 100%;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.medicalRecords-btn-save {
				width: 331rpx;
				height: 96rpx;
				background: #F0F0F0;
				border-radius: 48rpx;
				text-align: center;
				line-height: 96rpx;
				font-size: 32rpx;
				font-weight: 600;
				color: #666666;
			}

			.medicalRecords-btn-confirm {
				width: 331rpx;
				height: 96rpx;
				background: #FFD300;
				border-radius: 48rpx;
				// opacity: 0.3;
				text-align: center;
				font-size: 32rpx;
				font-weight: 600;
				color: #111111;
				line-height: 96rpx;
			}
		}
	}


	.htz-image-upload-Item-add {
		background: #F2F2F2;
		border-radius: 16rpx;
		width: 218rpx;
		height: 218rpx;
	}
</style>
